<template>
  <div class="login-container">
    <van-nav-bar title="微信授权登录" fixed placeholder />

    <div class="login-content">
      <div class="auth-loading">
        <van-loading size="24px" vertical>正在准备微信授权...</van-loading>
        <p v-if="errorMsg" class="error-msg">{{ errorMsg }}</p>
        <van-button
            v-if="showRetry"
            plain
            type="primary"
            size="small"
            @click="retryAuth"
        >
          重试
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getAuthAndRemove, setAuth,getToken,setAppId,getAppId } from '@/utils/auth'
import { getQueryString, getWeChatCallback } from '@/utils/wechatUtils'
import { Dialog, Toast } from 'vant'

export default {
  name: 'Login',
  data() {
    return {
      loading: true,
      errorMsg: '',
      showRetry: false
    }
  },
  created() {
    // 进入页面后自动开始授权流程
    this.startAuthProcess()
  },
  methods: {
    // 开始授权流程
    startAuthProcess() {
      this.loading = true
      this.errorMsg = ''
      this.showRetry = false
      // 检查是否是微信回调
      const appId = this.$route.query.appId || getQueryString('appId') || getAppId();
      if (!appId) {
        this.handleError('appId不能为空，异常代码10024')
        Dialog.alert({
          title: '微信授权异常',
          message: 'appId不能为空，异常代码10024'
        }).then(() => {
          this.$router.replace('/blank')
        })
        return
      }else {
        if (!getAppId()){
          setAppId(appId)
        }
      }
      const code = this.$route.query.code || getQueryString('code')
      const state = this.$route.query.state || getQueryString('state')
      const isWeChatOAuth = getAuthAndRemove()

      if (code && state && isWeChatOAuth) {
        this.handleWeChatCallback(code, state)
      } else {
        this.initWeChatAuth()
      }
    },

    // 初始化微信授权
    initWeChatAuth() {
      const appId = this.$store.getters.appId || this.$route.query.appId || getAppId();
      if (!appId) {
        this.handleError('appId不能为空，异常代码10023')
        Dialog.alert({
          title: '微信授权异常',
          message: 'appId不能为空，异常代码10023'
        }).then(() => {
          this.$router.replace('/401')
        })
        return
      }

      // 处理重定向路径
      let redirectUrl = this.$route.query.redirect || '/home'
      if (typeof redirectUrl === 'object') {
        try {
          const { path, query } = JSON.parse(redirectUrl)
          redirectUrl = path
          if (query && Object.keys(query).length > 0) {
            const queryStr = Object.keys(query)
                .map(key => `${key}=${encodeURIComponent(query[key])}`)
                .join('&')
            redirectUrl += `?${queryStr}`
          }
        } catch (e) {
          console.warn('解析redirect参数失败', e)
        }
      }

      this.$store.dispatch("GetAuthUrl", { appId, redirectUrl })
          .then(res => {
            if (res.data.code === 200) {
              setAuth(true)
             // window.location.href = res.data.data
            } else {
              throw new Error(res.data.message || '获取授权链接失败')
            }
          })
          .catch(err => {
            this.handleError(err.message || '微信授权初始化失败')
          })
    },

    // 处理微信回调
    handleWeChatCallback(code, state) {
      const appId = this.$store.getters.appId || this.$route.query.appId

      this.$store.dispatch("GetAuthUser", { appId, code, state })
          .then(() => {
            // 处理重定向
            let redirectPath = '/home'
            if (this.$route.query.route) {
              try {
                redirectPath = decodeURIComponent(this.$route.query.route)
              } catch (e) {
                console.warn('解析redirect参数失败', e)
              }
            }

            // 跳转到目标页面
            if (redirectPath.includes('?')) {
              const [path, queryStr] = redirectPath.split('?')
              const query = {}
              queryStr.split('&').forEach(pair => {
                const [key, value] = pair.split('=')
                if (key) query[key] = decodeURIComponent(value || '')
              })
              this.$router.replace({ path, query })
            } else {
              this.$router.replace(redirectPath)
            }
          })
          .catch(err => {
            this.handleError(err.message || '微信授权失败')
          })
    },

    // 错误处理
    handleError(message) {
      this.loading = false
      this.errorMsg = message
      this.showRetry = true
      Toast.fail(message)
    },

    // 重试授权
    retryAuth() {
      this.startAuthProcess()
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.login-content {
  flex: 1;
  padding: 30px 20px;
  display: flex;
  flex-direction: column;
}

.auth-loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.error-msg {
  margin-top: 15px;
  color: #f44;
  font-size: 14px;
}
</style>